<template>
  <div>

    <!-- 导航栏 -->
    <van-nav-bar
        title="购物车"
        left-text="返回"
        fixed
        left-arrow
        @click-left="onClickLeft"
    />

    <!-- 商品卡片 -->
    <van-checkbox-group v-model="result" style="margin-bottom:120px;margin-top:60px">
      <div v-for="item in cartList" :key="item.good.id">

        <van-checkbox :name="item"></van-checkbox>
        <van-swipe-cell>
          <van-card
              tag="标签"
              :price="item.good.actualPrice"
              :desc="item.good.desc"
              :title="item.good.title"
              :thumb="item.good.mainPic"
              :origin-price="item.good.originalPrice"
              style="margin:10px 5px"
          >
            <template #num>
              <van-stepper v-model="item.num" />
            </template>

          </van-card>
          <template #right>
            <van-button square text="删除" type="danger" class="delete-button" @click="del(item)" />
          </template>
        </van-swipe-cell>
      </div>
    </van-checkbox-group>

    <!-- 提交订单栏 -->
    <van-submit-bar :price="totalPrice" button-text="提交订单" @submit="onSubmit">
      <van-checkbox v-model="sellAll" @click="handlSellAll">全选</van-checkbox>
      <template #tip>
        你的收货地址不支持同城送, <span @click="onClickEditAddress">修改地址</span>
      </template>
    </van-submit-bar>

  </div>
</template>

<script>
export default {
  data(){
    return {
      sellAll:false,
      cartList:[],
      result:[],
      totalPrice:0
    }
  },
  watch:{
    cartList:{
      handler(list){
        localStorage.cartList = JSON.stringify(list)
      },
      deep:true
    },
    result:{
      handler(list){
        if(list.length == this.cartList.length){
          this.sellAll = true
        }else{
          this.sellAll = false
        }
        this.comtalPrice()
      },
      deep:true
    }
  },
  methods:{
    onSubmit() {
      location.href = "/";
    },
    onClickEditAddress(){

    },
    del(item){
      console.log(item)
      console.log(item.good)
      this.cartList.splice(item.good,1)
    },
    onClickLeft(){
      window.history.back()
    },
    handlSellAll(){
      if(this.sellAll){
        this.result = this.cartList
      }else{
        this.result = []
      }
    },
    comtalPrice(){
      let totalPrice = 0
      this.result.map((item)=>{
        totalPrice += item.good.actualPrice * item.num
      })
      this.totalPrice = totalPrice * 100
    }
  },
  created(){
    if(localStorage.cartList){
      this.cartList = JSON.parse(localStorage.cartList)
    }
  },

}
</script>

<style scoped>
.delete-button {
  height: 100%;
}
</style>
